﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Mindfor.Web.Routing;

namespace Mindfor.Web
{
	/// <summary>
	/// Repalces MasterView name to admin on actions that marked with <see cref="AdminLinkAttribute" />
	/// or sub-action of action with this attibute.
	/// </summary>
	public class AdminMasterReplaceFilter : IMvcFilter, IActionFilter
	{
		/// <summary>
		/// Gets or sets master view name to set to admin views.
		/// </summary>
		public static string MasterName { get; set; }

		/// <summary>
		/// When implemented in a class, gets a value that indicates whether multiple filters are allowed.
		/// </summary>
		public bool AllowMultiple
		{
			get { return false; }
		}

		/// <summary>
		/// When implemented in a class, gets the filter order.
		/// </summary>
		public int Order
		{
			get { return 0; }
		}

		/// <summary>
		/// Initializes static variables.
		/// </summary>
		static AdminMasterReplaceFilter()
		{
			MasterName = "~/Modules/Shared/_Admin.cshtml";
		}

		public void OnActionExecuting(ActionExecutingContext filterContext)
		{
		}

		public void OnActionExecuted(ActionExecutedContext filterContext)
		{
			ViewResult view = filterContext.Result as ViewResult;
			if (view != null)
			{
				// find attribute from action
				AdminLinkAttribute adminLinkAttribute = filterContext.ActionDescriptor.GetCustomAttributes<AdminLinkAttribute>(true).FirstOrDefault();
				if (adminLinkAttribute == null)
				{
					// find attribute from main action
					UrlSubActionAttribute subActionAttribute = filterContext.ActionDescriptor.GetCustomAttributes<UrlSubActionAttribute>(true).FirstOrDefault();
					if (subActionAttribute != null)
					{
						ActionDescriptor[] mainActions = filterContext.ActionDescriptor.ControllerDescriptor.GetCanonicalAction(subActionAttribute.MainAction);
						foreach (ActionDescriptor mainAction in mainActions)
						{
							adminLinkAttribute = mainAction.GetCustomAttributes<AdminLinkAttribute>(true).FirstOrDefault();
							if (adminLinkAttribute != null)
								break;
						}
					}
				}

				// replace master view
				if (adminLinkAttribute != null)
					view.MasterName = MasterName;
			}
		}
	}
}
